/*
Copyright 2022 The Authors of https://github.com/CDK-TEAM/CDK .

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package credential_access

import (
	"io/ioutil"
	"os"
	"regexp"
	"testing"

	"github.com/stretchr/testify/assert"
)

func captureStdout(f func()) string {
	rescueStdout := os.Stdout
	r, w, _ := os.Pipe()
	os.Stdout = w
	f()
	_ = w.Close()
	out, _ := ioutil.ReadAll(r)
	os.Stdout = rescueStdout
	return string(out)
}

func TestSearchLocalFileText(t *testing.T) {
	expectedStdout := `
found RSA private key in: ../../test/scan_file_text/1
[-----BEGIN RSA PRIVATE KEY-----]

found RSA private key in: ../../test/scan_file_text/xxx/2.txt
[-----BEGIN RSA PRIVATE KEY-----]

found Twilio API Key in: ../../test/scan_file_text/xxx/2.txt
[SKaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]

found AWS API Key in: ../../test/scan_file_text/xxx/2.txt
[AKIA99999999999999AB]
`

	actualStdout := captureStdout(func() {
		SearchLocalFileText("../../test")
	})

	pattern := regexp.MustCompile("found ")
	expParams := len(pattern.FindAllStringSubmatch(string(expectedStdout), -1))
	actParams := len(pattern.FindAllStringSubmatch(string(actualStdout), -1))

	assert.Equal(t, expParams, actParams, "That should be equal")
}
